package com.example.administrator.wallet.view.activity.mine.Contacts;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.acker.simplezxing.activity.CaptureActivity;
import com.example.administrator.wallet.R;
import com.example.administrator.wallet.constant.Api;
import com.example.administrator.wallet.intf.IRequestCallback;
import com.example.administrator.wallet.intf.IRequestManager;
import com.example.administrator.wallet.model.bean.ConcoinListBean;
import com.example.administrator.wallet.model.bean.ContactBean;
import com.example.administrator.wallet.model.helper.MySQLiteOpenDatabaseHelper;
import com.example.administrator.wallet.utils.DimbgUtils;
import com.example.administrator.wallet.utils.RequestFactory;
import com.example.administrator.wallet.utils.SharedPrefsUtil;
import com.google.gson.Gson;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import static com.example.administrator.wallet.R.id.rl_currency;
import static com.example.administrator.wallet.R.id.tv_content;
import static com.example.administrator.wallet.R.id.tv_currency;
import static com.loopj.android.http.AsyncHttpClient.log;

public class ModifyContactActivity extends AppCompatActivity {

    private ImageButton mIb_back,mIb_saoyisao;
    private TextView mV_title,mTv_currency;
    private RelativeLayout mRl_currency;
    private View view;
    private RelativeLayout mRl_add;
    private Button mBt_add_finish,mBt_delete;
    private EditText mEt_name,mEt_wallet_address,mEt_photo,mEt_emil,mEt_Remarks;
    private MySQLiteOpenDatabaseHelper dbHelper;// 数据库工具类
    private String contact_id = "";
    private String contact_name = "";
    private String contact_wallet_addr = "";
    private String contact_coin_symbol = "";
    private String contact_mobile = "";
    private String contact_email = "";
    private String contact_remark = "";
    private ContactBean contactBean;
    private int code = 0;
    IRequestManager reqequestManager = RequestFactory.getReqequestManager();
    private String token = "4dTl2756Gaq-EzW0dFXXWRRZJ7muxocA_1517070195";
    private ConcoinListBean concoinListBean;
    private SimpleAdapter adapter;
    private static final int REQ_CODE_PERMISSION = 0x1111;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_modify_contact);

        setStatuColor();
        mIb_back = (ImageButton) findViewById(R.id.finish_img);
        mV_title = (TextView) findViewById(R.id.view_title);
        mRl_currency = (RelativeLayout) findViewById(rl_currency);
        mRl_add = (RelativeLayout) findViewById(R.id.rl_add);
        mBt_add_finish = (Button) findViewById(R.id.bt_finish);
        mBt_delete = (Button) findViewById(R.id.bt_delete);
        mEt_name = (EditText) findViewById(R.id.et_name);
        mEt_wallet_address = (EditText) findViewById(R.id.et_wallet_address);
        mTv_currency = (TextView) findViewById(tv_currency);
        mEt_photo = (EditText) findViewById(R.id.et_photo);
        mEt_emil = (EditText) findViewById(R.id.et_emil);
        mEt_Remarks = (EditText) findViewById(R.id.et_Remarks);
        mIb_saoyisao = (ImageButton) findViewById(R.id.ib_saoyisao);

        dbHelper = new MySQLiteOpenDatabaseHelper(this);

        mIb_back.setVisibility(View.VISIBLE);
        mV_title.setText(R.string.ModifyaTheContact);

        Intent intent = getIntent();
        contact_name = intent.getStringExtra("name");
        contact_id =  intent.getStringExtra("id");
        contact_name = intent.getStringExtra("name");
        contact_wallet_addr = intent.getStringExtra("wallet_addr");
        contact_coin_symbol = intent.getStringExtra("coin_symbol");
        contact_mobile = intent.getStringExtra("mobile");
        contact_email = intent.getStringExtra("email");
        contact_remark = intent.getStringExtra("remark");

        mEt_name.setText(contact_name);
        mEt_wallet_address.setText(contact_wallet_addr);
        mTv_currency.setText(contact_coin_symbol);
        mEt_photo.setText(contact_mobile);
        mEt_emil.setText(contact_email);
        mEt_Remarks.setText(contact_remark);


        mRl_currency.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                //SharedPrefsUtil.getValue(ModifyContactActivity.this,"wallet", "token",""
                //token
                reqequestManager.httpPost(Api.BaseUrl + Api.Coin_List, Api.getCoinList(SharedPrefsUtil.getValue(ModifyContactActivity.this,"wallet", "token",""),"0"), new IRequestCallback(){
                    @Override
                    public void onSuccess(String Response) {
                        Gson gson = new Gson();
                        concoinListBean = gson.fromJson(Response, ConcoinListBean.class);
                        code = concoinListBean.getCode();
                        if (code == 200){

                            initCurrency();

                        }else if(code == 501){
                            Toast.makeText(getApplicationContext(),R.string.notype,Toast.LENGTH_SHORT).show();
                        }else {
                            Toast.makeText(getApplicationContext(),code +"",Toast.LENGTH_SHORT).show();
                        }
                    }
                    @Override
                    public void onFailure(String error) {
                    }
                });

            }
        });

        mIb_saoyisao.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (ContextCompat.checkSelfPermission(ModifyContactActivity.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(ModifyContactActivity.this, new String[]{Manifest.permission.CAMERA}, REQ_CODE_PERMISSION);
                } else {
                    startCaptureActivityForResult();
                }

            }
        });
        mBt_add_finish.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String modify_name = mEt_name.getText().toString();
                String modify_wallet_addr = mEt_wallet_address.getText().toString();
                String modify_coin_symbol = mTv_currency.getText().toString();
                String modify_mobile = mEt_photo.getText().toString();
                String modify_email = mEt_emil.getText().toString();
                String modify_remark = mEt_Remarks.getText().toString();

                if ("".equals(modify_name) | "".equals(modify_wallet_addr)){
                    Toast.makeText(getApplicationContext(),R.string.notAddressandname,Toast.LENGTH_SHORT).show();
                }else{
                    reqequestManager.httpPost(Api.BaseUrl + Api.Modify_Contact, Api.getModifyContact(SharedPrefsUtil.getValue(ModifyContactActivity.this,"wallet", "token",""),contact_id,modify_name,modify_wallet_addr,modify_coin_symbol,modify_mobile,modify_email,modify_remark), new IRequestCallback(){
                        @Override
                        public void onSuccess(String Response) {
                            Gson gson = new Gson();
                            contactBean = gson.fromJson(Response, ContactBean.class);
                            code = contactBean.getCode();
                            log.e("tag",code+"");
                            if (code == 200) {
                                startActivity(new Intent(ModifyContactActivity.this,HasContactActivity.class));
                                    Toast.makeText(getApplicationContext(),R.string.Modifiedsuccessfully,Toast.LENGTH_SHORT).show();
                                finish();
                                overridePendingTransition(R.anim.pre_in_anim, R.anim.pre_out_anim);


                            } else if(code == 500){
                                Toast.makeText(ModifyContactActivity.this,R.string.Failedtomodifycontact+code,Toast.LENGTH_SHORT).show();
                                finish();
                                overridePendingTransition(R.anim.pre_in_anim, R.anim.pre_out_anim);


                            }else if(code == 501){
                                Toast.makeText(ModifyContactActivity.this,R.string.pleasetryagain+code,Toast.LENGTH_SHORT).show();
                                finish();
                                overridePendingTransition(R.anim.pre_in_anim, R.anim.pre_out_anim);


                            }
                        }
                        @Override
                        public void onFailure (String error){
                        }

                    });
                }

            }
        });
        mBt_delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                reqequestManager.httpPost(Api.BaseUrl + Api.Delete_Contact, Api.getDeleteContact(SharedPrefsUtil.getValue(ModifyContactActivity.this,"wallet", "token",""),contact_id), new IRequestCallback(){
                    @Override
                    public void onSuccess(String Response) {
                        Gson gson = new Gson();
                        contactBean = gson.fromJson(Response, ContactBean.class);
                        code = contactBean.getCode();
                        log.e("tag",code+"");
                        if (code == 200) {
                            Toast.makeText(ModifyContactActivity.this, R.string.Deletingsuccessful, 0).show();
                            startActivity(new Intent(ModifyContactActivity.this,HasContactActivity.class));
                            finish();
                            overridePendingTransition(R.anim.pre_in_anim, R.anim.pre_out_anim);


                        } else if(code == 500){
                            Toast.makeText(ModifyContactActivity.this, R.string.DeleteFailed, 0).show();
                            finish();
                            overridePendingTransition(R.anim.pre_in_anim, R.anim.pre_out_anim);


                        }else if(code == 501){
                            Toast.makeText(ModifyContactActivity.this,R.string.dele_pleasetryagain+code,Toast.LENGTH_SHORT).show();
                            finish();
                            overridePendingTransition(R.anim.pre_in_anim, R.anim.pre_out_anim);


                        }
                    }
                    @Override
                    public void onFailure (String error){
                        Toast.makeText(ModifyContactActivity.this, "删除联系人失败", Toast.LENGTH_SHORT).show();
                        finish();
                        overridePendingTransition(R.anim.next_in_anim, R.anim.next_out_anim);

                    }

                });
            }
        });
        mIb_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               onBackPressed();
            }
        });

    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        startActivity(new Intent(ModifyContactActivity.this,HasContactActivity.class));
        finish();
        overridePendingTransition(R.anim.pre_in_anim, R.anim.pre_out_anim);

    }
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case CaptureActivity.REQ_CODE:
                switch (resultCode) {
                    case RESULT_OK:
                        Toast.makeText(this, data.getStringExtra(CaptureActivity.EXTRA_SCAN_RESULT), Toast.LENGTH_SHORT).show();
//                        Log.e("TAG---ewm", "onActivityResult: " + data.getStringExtra(CaptureActivity.EXTRA_SCAN_RESULT));
                        mEt_wallet_address.setText(data.getStringExtra(CaptureActivity.EXTRA_SCAN_RESULT));
                        break;
                    case RESULT_CANCELED:
                        if (data != null) {
                            Toast.makeText(this, data.getStringExtra(CaptureActivity.EXTRA_SCAN_RESULT), Toast.LENGTH_SHORT).show();
//                            Log.e("TAG---ewm", "onActivityResult: " + data.getStringExtra(CaptureActivity.EXTRA_SCAN_RESULT));
                            mEt_wallet_address.setText(data.getStringExtra(CaptureActivity.EXTRA_SCAN_RESULT));
                        }
                        break;
                    case 101:
                        if(data!=null){
                            mEt_wallet_address.setText("");
                            String addr = data.getStringExtra("addr");
                            mEt_wallet_address.setText(addr);
                        }
                        break;
                }
                break;
        }
    }
    private void startCaptureActivityForResult() {
        Intent intent = new Intent(ModifyContactActivity.this, CaptureActivity.class);
        Bundle bundle = new Bundle();
        bundle.putBoolean(CaptureActivity.KEY_NEED_BEEP, CaptureActivity.VALUE_BEEP);
        bundle.putBoolean(CaptureActivity.KEY_NEED_VIBRATION, CaptureActivity.VALUE_VIBRATION);
        bundle.putBoolean(CaptureActivity.KEY_NEED_EXPOSURE, CaptureActivity.VALUE_NO_EXPOSURE);
        bundle.putByte(CaptureActivity.KEY_FLASHLIGHT_MODE, CaptureActivity.VALUE_FLASHLIGHT_OFF);
        bundle.putByte(CaptureActivity.KEY_ORIENTATION_MODE, CaptureActivity.VALUE_ORIENTATION_AUTO);
        bundle.putBoolean(CaptureActivity.KEY_SCAN_AREA_FULL_SCREEN, CaptureActivity.VALUE_SCAN_AREA_FULL_SCREEN);
        bundle.putBoolean(CaptureActivity.KEY_NEED_SCAN_HINT_TEXT, CaptureActivity.VALUE_SCAN_HINT_TEXT);
        intent.putExtra(CaptureActivity.EXTRA_SETTING_BUNDLE, bundle);
        startActivityForResult(intent, CaptureActivity.REQ_CODE);
    }
    private void initCurrency() {
        view = View.inflate(this, R.layout.popup_currency, null);
        final ListView lv_coin_list = (ListView) view.findViewById(R.id.lv_coin_list);
        final Button bt_cancel = (Button) view.findViewById(R.id.bt_cancel);

        new Handler().post(new Runnable() {
            @Override
            public void run() {
                final PopupWindow window = new PopupWindow(view, RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT, true);
                window.setFocusable(true);
                window.setTouchable(true);
                window.setOutsideTouchable(true);
                window.showAtLocation(mRl_add, Gravity.CENTER, 0, 0);
                Log.e("TAG-----", "OK");
                DimbgUtils.dimBackground(ModifyContactActivity.this, 0.5f);
                window.setOnDismissListener(new PopupWindow.OnDismissListener() {
                    @Override
                    public void onDismiss() {
                        DimbgUtils.dimBackground(ModifyContactActivity.this, 1.0f);
                    }
                });

                List<ConcoinListBean.DataBean> datas1=new ArrayList<>();
                datas1.addAll(concoinListBean.getData());
                List<HashMap<String,Object>> list = new ArrayList<HashMap<String, Object>>();
                for (int i = 0; i < datas1.size(); i++) {
                    HashMap<String,Object> map = new HashMap<String,Object>();
                    ConcoinListBean.DataBean data1Bean = datas1.get(i);
                    map.put("coin",data1Bean.getSymbol());
                    list.add(map);
                }

                adapter = new SimpleAdapter(ModifyContactActivity.this,list, R.layout.item_conlist,new String[]{"coin"},new int[]{tv_content});
                lv_coin_list.setAdapter(adapter);

                lv_coin_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        TextView content = (TextView) view.findViewById(R.id.tv_content);
                        mTv_currency.setText(content.getText().toString());
                        window.dismiss();

                    }
                });
                bt_cancel.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        window.dismiss();
                    }
                });


            }
        });

    }

    public void setStatuColor() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            Window window = getWindow();
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(getResources().getColor(android.R.color.white));
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        }
        setMiuiStatusBarDarkMode(this, true);
        setMiuiStatusBarDarkMode(this, true);
    }

    //设置成白色的背景，字体颜色为黑色。
    public static boolean setMiuiStatusBarDarkMode(Activity activity, boolean darkmode) {
        Class<? extends Window> clazz = activity.getWindow().getClass();
        try {
            int darkModeFlag = 0;
            Class<?> layoutParams = Class.forName("android.view.MiuiWindowManager$LayoutParams");
            Field field = layoutParams.getField("EXTRA_FLAG_STATUS_BAR_DARK_MODE");
            darkModeFlag = field.getInt(layoutParams);
            Method extraFlagField = clazz.getMethod("setExtraFlags", int.class, int.class);
            extraFlagField.invoke(activity.getWindow(), darkmode ? darkModeFlag : 0, darkModeFlag);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    public static boolean setMeizuStatusBarDarkIcon(Activity activity, boolean dark) {
        boolean result = false;
        if (activity != null) {
            try {
                WindowManager.LayoutParams lp = activity.getWindow().getAttributes();
                Field darkFlag = WindowManager.LayoutParams.class
                        .getDeclaredField("MEIZU_FLAG_DARK_STATUS_BAR_ICON");
                Field meizuFlags = WindowManager.LayoutParams.class
                        .getDeclaredField("meizuFlags");
                darkFlag.setAccessible(true);
                meizuFlags.setAccessible(true);
                int bit = darkFlag.getInt(null);
                int value = meizuFlags.getInt(lp);
                if (dark) {
                    value |= bit;
                } else {
                    value &= ~bit;
                }
                meizuFlags.setInt(lp, value);
                activity.getWindow().setAttributes(lp);
                result = true;
            } catch (Exception e) {
            }
        }
        return result;
    }
}
